package com.corpgovernment.supplier.service;

import static com.corpgovernment.permission.config.PermissionFilter.DATA_PERMISSION_ORG_ID_LIST;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.corpgovernment.api.organization.model.org.OrgInfoVo;
import com.corpgovernment.api.organization.model.org.request.GetOrgConfigRequest;
import com.corpgovernment.api.organization.model.org.response.GetOrgConfigResponse;
import com.corpgovernment.common.base.BaseService;
import com.corpgovernment.common.base.JSONResult;
import com.corpgovernment.common.utils.BaseUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.corpgovernment.common.utils.Null;
import com.corpgovernment.organization.entity.db.MbOrgInfo;
import com.corpgovernment.organization.service.IOrgConfigService;
import com.corpgovernment.organization.service.IOrganizationInfoService;
import com.corpgovernment.supplier.dto.SupplementInfoDto;
import com.corpgovernment.supplier.entity.db.SupplierCompany;
import com.corpgovernment.supplier.enums.ProductTypeForIdEnum;
import com.corpgovernment.supplier.mapper.SupplierCompanyMapper;
import com.corpgovernment.supplier.vo.QuerySupplementListReqVo;
import com.corpgovernment.supplier.vo.QuerySupplementListRspVo;
import com.corpgovernment.supplier.vo.SupplementInfoVo;
import com.ctrip.corp.obt.generic.core.context.RequestContext;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.ctrip.corp.obt.shard.context.PageContext;
import com.ctrip.corp.obt.shard.sql.mybatis.interceptor.pagination.IPage;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class IMbSupplierCompanySericeImpl extends BaseService{

    @Resource
    private SupplierCompanyMapper mbSupplierCompanyMapper;

    @Autowired
    private IOrganizationInfoService organizationInfoService;

   @Autowired
   private IOrgConfigService orgConfigService;


    public QuerySupplementListRspVo getSupplementList(QuerySupplementListReqVo reqVo) {
        QuerySupplementListRspVo rspVo = new QuerySupplementListRspVo();
        try {
            initElkLog();


            //1，通过supplier_code查找关联的公司orgIds。
            List<SupplierCompany> mbSupplierCompanies = mbSupplierCompanyMapper.selectProductBySupplierCode(reqVo.getSupplierCode(), reqVo.getCompanyName());
            if (CollectionUtils.isEmpty(mbSupplierCompanies)) {
                return getErrorData(reqVo.getPageNum(), reqVo.getPageSize());
            }

            addElkInfoLog("查询到关联企业 %s", JsonUtils.toJsonString(mbSupplierCompanies));

            //2，通过orgIds递归查询下面的所有子部门。
            //判断是否根据公司名称模糊查询   如模糊查询需根据公司id查询出公司名称进行筛选
            List<String> orgIds = mbSupplierCompanies.stream().map(SupplierCompany::getCompanyCode)
                    .filter(StringUtils::isNotBlank).collect(Collectors.toList());

            addElkInfoLog("查询到的关联企业orgId %s", JsonUtils.toJsonString(orgIds));

            JSONResult<Map<String, List<String>>> jsonResult = this.listAllGroupDepartmentIds(orgIds, Boolean.FALSE);
            if (jsonResult == null || !jsonResult.isSUCCESS() || jsonResult.getData() == null) {
                return getErrorData(reqVo.getPageNum(), reqVo.getPageSize());
            }

            addElkInfoLog("查询到的所有子部门 %s", JsonUtils.toJsonString(jsonResult.getData()));

            //3，通过所有子部门orgId和其他条件分页查找员工信息。
            List<String> deptIds = Lists.newArrayList();
            jsonResult.getData().forEach((k, v) -> deptIds.addAll(v));
            if (CollectionUtils.isEmpty(deptIds)) {

                return getErrorData(reqVo.getPageNum(), reqVo.getPageSize());
            }
            // 获取配置的orgId 列表
            List<String> listOrgIds = getListOrgIds();
            List<String> deptIdParams;
            if (CollectionUtils.isNotEmpty(listOrgIds)) {
                // 取交集
                deptIdParams = deptIds.stream().filter(listOrgIds::contains).collect(Collectors.toList());
            } else {
                deptIdParams = deptIds;
            }
            log.info("最终查询的部门id为：{}", JsonUtils.toJsonString(deptIdParams));
            List<String> finalDeptIdParams = deptIdParams;
            IPage<SupplementInfoDto> page = PageContext.startPage(reqVo.getPageNum(), reqVo.getPageSize() == 0 ? 10 : reqVo.getPageSize(),
                    () -> mbSupplierCompanyMapper.queryEmployeeList(finalDeptIdParams, reqVo.getAccount(), reqVo.getName(), reqVo.getPhone()));
            rspVo.setCount(page.getTotal());
            rspVo.setCurrentPage((int) page.getCurrent());
            rspVo.setTotalPage((int) page.getPages());
            rspVo.setPageSize((int) page.getSize());
            rspVo.setList(Lists.newArrayList());
            List<SupplementInfoDto> list = page.getRecords();
            if (CollectionUtils.isEmpty(list)) {
                return rspVo;
            }

            addElkInfoLog("列表查询出数据 %s", JsonUtils.toJsonString(list));

            //4通过DeptId获取最近公司的OrgId,查询公司名称
            Map<String, String> depCompanyMap = new HashMap();
            for (SupplementInfoDto dto : list) {
                dto.setAccountName(dto.getAccountName().startsWith("+86")?dto.getAccountName().substring(3):dto.getAccountName());
                String deptId = dto.getDeptId();
                if (!depCompanyMap.containsKey(deptId)) {
                    jsonResult.getData().forEach((key, value) -> {
                        if (value.contains(deptId)) {
                            depCompanyMap.put(deptId, key);
                        }
                    });
                }
            }

            //获取公司名称
            Map<String, OrgInfoVo> orgInfoMap = new HashMap<>();
            List<String> companyIds = depCompanyMap.values().stream().distinct().collect(Collectors.toList());
            JSONResult<List<OrgInfoVo>> companyInfoResult = this.findByOrgIdList(companyIds);

            if (companyInfoResult != null && companyInfoResult.isSUCCESS() && companyInfoResult.getData() != null) {
                List<OrgInfoVo> companyList = companyInfoResult.getData();
                orgInfoMap.putAll(companyList.stream().collect(Collectors.toMap(OrgInfoVo::getOrgId, Function.identity())));
            }

            //5,封装给前端
            Map<String, SupplierCompany> productMap = mbSupplierCompanies.stream().collect(Collectors.toMap(SupplierCompany::getCompanyCode, Function.identity()));
            for (SupplementInfoDto dto : list) {
                SupplementInfoVo supplementInfoVo = new SupplementInfoVo();
                supplementInfoVo.setName(dto.getName());
                supplementInfoVo.setAccount(dto.getAccount());
                supplementInfoVo.setDepartment(dto.getDepartment());
                supplementInfoVo.setPhone(dto.getPhone());
                supplementInfoVo.setOrgId(dto.getDeptId());
                supplementInfoVo.setAccountName(dto.getAccountName());
                // 获取是否必填成本中心或项目号
                GetOrgConfigRequest getOrgConfigRequest = new GetOrgConfigRequest();
                getOrgConfigRequest.setOrgId(dto.getDeptId());
                if (dto.getDeptId() != null) {
                    Optional.ofNullable(orgConfigService.getOrgConfig(getOrgConfigRequest))
                            .map(GetOrgConfigResponse::getOrgConfigInfo)
                            .ifPresent(orgConfigInfoVo -> {
                                supplementInfoVo.setCostCenterIsRequired(orgConfigInfoVo.getCostCenterIsVerify());
                                supplementInfoVo.setProjectIsRequired(orgConfigInfoVo.getProjectIsVerify());
                            });
                }
                if (depCompanyMap.containsKey(dto.getDeptId())) {
                    String orgId = depCompanyMap.get(dto.getDeptId());
                    if (orgInfoMap.containsKey(orgId)) {
                        OrgInfoVo orgInfoVo = orgInfoMap.get(orgId);
                        supplementInfoVo.setCompany(orgInfoVo.getName());
                    }
                    if (productMap.containsKey(orgId)) {
                        String productType = productMap.get(orgId).getProductType();
                        if (!StringUtils.isEmpty(productType)) {
                            supplementInfoVo.setProducts(Lists.newArrayList());
                            String[] split = productType.split(",");
                            for (String s : split) {
                                if (ProductTypeForIdEnum.getKey(s) == null) {
                                    continue;
                                }
                                supplementInfoVo.getProducts().add(ProductTypeForIdEnum.getKey(s));
                            }
                        }
                    }
                }
                rspVo.getList().add(supplementInfoVo);
            }
            rspVo.getList().stream().sorted(Comparator.comparing(item -> item.getName()));
            return rspVo;
        } finally {
            log.info("查询订单补录列表  request :{}", getElkInfoLog());
            clearElkLog();
        }
    }

    private List<String> getListOrgIds() {
        Object orgIds = RequestContext.getCurrentContext().getContextParams(DATA_PERMISSION_ORG_ID_LIST);
        List<String> listOrgIds = new ArrayList<>();
        if (Objects.nonNull(orgIds)) {
            String str = JsonUtils.toJsonString(orgIds);
            if (StringUtils.isNotBlank(str)) {
                log.info("获取到的数据权限为：{}", str);
                listOrgIds = JsonUtils.parseArray(str, String.class);
            }
        }
        return listOrgIds;
    }

    private JSONResult<List<OrgInfoVo>> findByOrgIdList(List<String> companyIds) {
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(companyIds)) {
            // 查询组织结构信息
            List<MbOrgInfo> mbOrgInfoList = organizationInfoService.listByOrgIds(companyIds);

            if (!org.apache.commons.collections.CollectionUtils.isEmpty(mbOrgInfoList)) {

                ArrayList<OrgInfoVo> list = Lists.newArrayList();
                mbOrgInfoList.forEach(o -> {
                    OrgInfoVo orgInfoVo = new OrgInfoVo();
                    BeanUtils.copyProperties(o, orgInfoVo);
                    list.add(orgInfoVo);
                });
                return JSONResult.success(list);
            }
            return JSONResult.errorMsg("query db return empty");
        }
        return JSONResult.errorMsg("orgIds is empty");
    }

    private JSONResult<Map<String, List<String>>> listAllGroupDepartmentIds(List<String> orgIds, Boolean aFalse) {
        Map<String, List<String>> result = Maps.newHashMap();
        if (!BaseUtils.isNotNull(orgIds)) {
            log.info("orgIds为空");
            return JSONResult.success(result);
        }
        orgIds.forEach(orgId -> {
            List<String> data = organizationInfoService.listAllDepartmentIds(orgId, false);
            if (data == null) {
                data = Lists.newArrayList();
            }
            data.add(orgId);
            result.put(orgId, data);
        });
        return JSONResult.success(result);
    }
    public QuerySupplementListRspVo getErrorData (Integer currentPage, Integer pageSize) {
        QuerySupplementListRspVo response = new QuerySupplementListRspVo();
        response.setCount(0L);
        response.setCurrentPage(currentPage);
        response.setPageSize(pageSize);
        response.setTotalPage(0);
        response.setList(Lists.newLinkedList());
        return response;
    }
}
